// write.js
import Promise from '../../utils/es6-promise.min.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    size: 30,
    title: '',
    text: '',
    img_list: [],
    uploadImage:'',
    address: '',
    img:{},
    // showInput: false
  },
  title_input(e) {
    console.log(e.detail.value)
    let num = 30 - e.detail.value.length
    this.setData({
      title: e.detail.value,
      size: num
    })
  },
  textarea_input(e) {
    this.setData({
      text: e.detail.value
    })
  },
  address() {
    let self = this
    wx.chooseLocation({
      success: function (res) {
        self.setData({
          address: res.name
        })
      }
    })
  },
  upload() {
    let self = this
    let arr = self.data.img_list

    wx.chooseImage({
      success: function (res) {
        if (arr.length >= 5) {
          wx.showToast({
            title: '最多只能选5张图片哦',
            image:'../../image/error.png'
          })
        } else {
          let img = res.tempFilePaths
          
          self.setData({
            img_list: arr.concat(img)
          })
        }
      }
    })
  },
  showImg(e) {
    let self = this
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: self.data.img_list
    })
  },
  submit() {
    wx.showLoading({
      title: '正在发布...',
      //  mask: true
    })
    let baseUrl = getApp().globalData.baseUrl,
        access_token = getApp().globalData.access_token,
        header = getApp().globalData.header,
        title = this.data.title,
        content = this.data.text,
        address = this.data.address,
        order_id = this.data.options ? this.data.options:null
        // 上传图片
    this.uploadImage(images => {
      wx.request({
        url: baseUrl + '/Journal/post_note',
        method: 'post',
        header,
        data: { access_token, title, content, address, images, order_id},
        success: res => {
          console.log(res.data,'****************')
            if (res.data.code == 200) {
              wx.hideLoading()
              wx.showToast({
                title: '发布成功！',
              })
              wx.switchTab({
                url: '../index/index'
              })
            } else { 
              wx.hideLoading()
              wx.showToast({
                title: res.data.message
              })
            }
    
        }
      })
    })
  },
  uploadImage(callback){
    let self = this, 
      baseUrl = getApp().globalData.baseUrl,
      access_token = getApp().globalData.access_token,
      header = getApp().globalData.header,
      tempFilePaths = this.data.img_list
    console.log(tempFilePaths)
    function uploadTask(path,obj,index){
      return new Promise((resolve, reject) => {
        const uploadTask_ = wx.uploadFile({
          url: baseUrl + '/Journal/post_images', //仅为示例，非真实的接口地址
          filePath: path,
          name: 'images',
          formData: { access_token },
          success: function (res) {
            res.data = JSON.parse(res.data)
            if (res.data.code == 200) {
              obj = obj || {}
              obj[index] = res.data.data
              resolve(obj)
            }else{
              reject()
            }
          },
          fail(res){
            console.log(res,'*************')
          }
        })
      })
    } 
    var  obj = {}
    var uploadImage = ''
    var promises  =  tempFilePaths.map( (path,index) => {
      if (path.indexOf('wxfile') == 0){
        return uploadTask(path, obj, index)
      }else{
        path = path.split('upload/')[1]
        index == 0 ? (uploadImage += path) : (uploadImage += ',' + path)
      }
    })
    Promise.all(promises).then(res => {
      console.log(obj)
      for(let i in obj){
        i == 0 ? (uploadImage += obj[i] ):(uploadImage += ',' + obj[i])
      }
      callback(uploadImage )
    }).catch( res => {
      console.log(res)
    })
    
  },
  // showInput() {
  //   this.setData({
  //     showInput: true
  //   })
  //   console.log(999)
  // },
  // msk(e) {
  //   if (e.target.dataset.name == 'msk') {
  //     this.setData({
  //       showInput: false
  //     })
  //   } else return
  // },
  del(e){
    let self = this
    wx.showActionSheet({
      itemList: ['删除'],
      success: function(res){
        if (res.tapIndex==0){
          // console.log(e.currentTarget.dataset.index)
          let index = e.currentTarget.dataset.index
          let arr = self.data.img_list
          arr.splice(index,1)
          self.setData({
            img_list: arr
          })
        }
      }
    })
  },
  // 获取商品的图片
  getProductImg(){
    let baseUrl = getApp().globalData.baseUrl,
        access_token = getApp().globalData.access_token,
        self = this,
        order_id = this.data.options
    wx.request({
      url: baseUrl + '/MyOrder/detail',
      method: 'GET',
      data: { access_token, order_id},
      success: data =>{
        console.log(data.data.data.productInfo)
        let productImg = []
        data.data.data.productInfo.forEach( value => {
          value.images.photo.forEach( value2 => {
            productImg.push(value2.url)
          })
        })
        console.log(productImg)
        self.setData({
          img_list: productImg
        })
      }
    })
  },
  // 
  onLoad(options){
    let self = this
    if(options.id){
      this.setData({
        options: options.id
      },function(){
        self.getProductImg()
      })
      
    }
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
})